package com.sgj;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * @author 沈国纪
 * @date 2020/11/25 20:20
 */
public class TestTX {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("101.132.152.66",6379);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","world");
        jsonObject.put("name","shenguoji");

        // 开启事务
        Transaction multi = jedis.multi();
        String result = jsonObject.toJSONString();

        try {

            multi.set("user1",result);
            multi.set("user2",result);

            //代码抛出异常事务，执行失败！
            int i = 1/0;

            // 执行事务
            multi.exec();

        } catch (Exception e) {
            //放弃事务
            multi.discard();

            e.printStackTrace();
        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));

            // 关闭连接
            jedis.close();
        }

    }
}
